<?php
if (!defined('IN_IPB')) exit("<h1>Incorrect access</h1> You may not access this file without the acp.");

class raffle extends template_plugin
{
	var $ipsclass;
	
	var $name = "Raffle";
	var $multiple = 0;
	var $cache_array = array(
								'ibm_raffle' => array('Raffle cache','raffle_cache'),
							 );
	
	var $settings = array();
	var $odds = array();
	
	function raffle_cache()
	{
		$this->ipsclass->cache['ibm_raffle'] = array();
		
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_raffle','where'=>"r_status != 'drawn'"));
		$this->ipsclass->DB->exec_query();
		while($raffle = $this->ipsclass->DB->fetch_row())
		{
			$raffle['prizes'] = unserialize($raffle['prizes']);
			$this->ipsclass->cache['ibm_raffle'][$raffle['r_id']] = $raffle;
		}
		
		$this->ipsclass->update_cache( array( 'name' => 'ibm_raffle', 'array' => 1, 'deletefirst' => 1 ) );
	}
	
	function acp_menu()
	{
		return array(
					  1 => array('Current Raffles','code=plugin&do=run&link='.$this->plugin['link']),
					  2 => array('Previous Raffles','code=plugin&do=run&link='.$this->plugin['link'].'&action=previous'),
					);
	}
	
	function _load(&$plugin)
	{
		parent::_load($plugin);
		
		if($plugin['link'])
		{
			$this->settings = unserialize($plugin['plugin_config']);
		}
		else
		{
			$this->settings['send_pm'] = 1;
			$this->settings['win_subject'] = "You have just won the raffle";
			$this->settings['win_message'] = 
<<<EOF
{member_name},

You have just won the lottery, [url={base_url}index.php?autocom=market&plugin={plugin}&lottery={raffle_id}]{raffle_name}[/url]

[b]This is an automated message[/b]
EOF;
		}
		
		if(!is_array($this->ipsclass->cache['ibm_raffle']))
		{
			$this->ipsclass->cache['ibm_raffle'] = array();
		}
		
		$time = time();
		$loaded = 0;
		if(IPB_THIS_SCRIPT == 'public' && $this->ipsclass->input['request_method'] != 'post')
		{
			foreach($this->ipsclass->cache['ibm_raffle'] as $id => $raffle)
			{
				if($raffle['end_time'] <= $time)
				{
					if(!$loaded)
					{
						$this->ipsclass->DB->load_cache_file(ROOT_PATH.'sources/market/sql/'.$this->ipsclass->vars['sql_driver'].'_plugin_queries.php','sql_plugin_queries');
						
						$loaded = 1;
					}
					
					$count = 0;
					foreach($raffle['prizes']['winner'] as $c)
					{
						$count += $c;
					}
					
					$set = 0;
					$set_limit = $raffle['prizes']['winner'][$set];
					$t = 0;
					$this->ipsclass->DB->build_query_from_cache('raffle_select_random_tickets',array('raffle'=>$id,'tickets'=>$count),'sql_plugin_queries');
					$q = $this->ipsclass->DB->exec_query();
					while($ticket = $this->ipsclass->DB->fetch_row($q))
					{
						if($raffle['prizes']['money'][$set])
						{
							$this->ipsclass->DB->build_and_exec_query(array('update'=>'members','set'=>$this->ipsclass->vars['market_members_field']."=".$this->ipsclass->vars['market_members_field']."+".$raffle['prizes']['money'][$set],'where'=>"id=".$ticket['member_id']));
							
							$this->ipsclass->market_class->record_reward($raffle['prizes']['money'][$set],$raffle['end_time']);
						}
						if($raffle['prizes']['items'][$set])
						{
							foreach($raffle['prizes']['items'][$set] as $item_id => $quanity)
							{
								$expired = $this->ipsclass->cache['market_items'][$item_id]['expire_time'] > 0 ? $time + $this->ipsclass->cache['market_items'][$item_id]['expire_time'] * $this->ipsclass->cache['market_items'][$item_id]['expire_unit'] : 0;
								for($i = 0; $i < $quanity; $i++)
								{
									$inv_item = array(
														'member_id' => $ticket['member_id'],
														'item' => $item_id,
														'price_bought' => $this->ipsclass->cache['market_items'][$item_id]['price'],
														'resell_price' => $this->ipsclass->cache['market_items'][$item_id]['resell'],
														'time_bought' => $time,
														'settings' => '',
														'expired' => $expired,
													);
									if($this->ipsclass->market_class->items_loaded[$item_id]->public_on_create_item($inv_item))
									{
										$this->ipsclass->DB->do_insert('market_inventory',$inv_item);
									}
								}
							}
						}
						
						if($this->settings['send_pm'])
						{
							$subject = $this->settings['win_subject'];
							$message = $this->settings['win_message'];
							
							$member = $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'members','where'=>"id=".$ticket['member_id']));
							$message = str_replace("{member_name}",$member['members_display_name'],$message);
							$message = str_replace("{base_url}",$this->ipsclass->base_url,$message);
							$message = str_replace("{plugin}",$this->plugin['link'],$message);
							$message = str_replace("{raffle_name}",$raffle['r_name'],$message);
							
							if($this->settings['send_pm'] == 1)
							{
								require_once( ROOT_PATH.'sources/lib/func_msg.php' );
						 		
								$msg_lib           =  new func_msg();
								$msg_lib->ipsclass =& $this->ipsclass;
								$msg_lib->init();
								
								$msg_lib->to_by_id    = $member['id'];
								$msg_lib->from_member = $member;
								$msg_lib->msg_title   = $subject;
								$msg_lib->msg_post    = $this->ipsclass->parser->pre_display_parse( $this->ipsclass->parser->pre_db_parse( $message ) );
								$msg_lib->force_pm    = 1;
								
								$msg_lib->send_pm();
							}
							else
							{
								require_once( ROOT_PATH."sources/classes/class_email.php" );
								
								$email           =  new emailer();
								$email->ipsclass =& $this->ipsclass;
								$email->email_init();
								
								$email->subject = $subject;
								$email->message = $this->ipsclass->parser->pre_display_parse( $this->ipsclass->parser->pre_db_parse( $message ) );
								$email->to      = $member['email'];
						
								$email->send_mail();
							}
						}
						
						if(++$t == $set_limit)
						{
							$set_limit = $this->ipsclass->cache['ibm_raffle']['prizes']['winner'][++$set];
						}
					}
					
					$this->ipsclass->DB->do_update('market_raffle',array(
																			'r_status' => 'drawn',
													),"r_id=".$id);
					
					if($raffle['continuous'])
					{
						$new_raffle = $raffle;
						
						$diff = $raffle['end_time'] - $raffle['start_time'];
						$diff2 = $raffle['start_time'] - $raffle['create_time'];
						if($new_raffle['continuous'] == 1)
						{
							$new_raffle['create_time'] = $raffle['end_time'] - $diff2;
							$new_raffle['start_time'] = $raffle['end_time'];
						}
						else
						{
							$new_raffle['create_time'] = $raffle['end_time'];
							$new_raffle['start_time'] = $raffle['create_time'] + $diff2;
						}
						$new_raffle['end_time'] = $new_raffle['start_time'] + $diff;
						
						if($new_raffle['stock_tickets'] >= 0)
						{
							$new_raffle['stock_tickets'] += 0;
						}
						
						$new_raffle['prizes'] = serialize($new_raffle['prizes']);
						unset($new_raffle['r_id']);
						$this->ipsclass->DB->do_insert('market_raffle',$new_raffle);
					}
					
					$this->raffle_cache();
					break;
				}
			}
		}
		
		foreach($this->ipsclass->cache['ibm_raffle'] as $i => $raffle)
		{
			if($raffle['start_time'] > $time && IPB_THIS_SCRIPT == 'public')
			{
				$this->ipsclass->cache['ibm_raffle'][$i]['r_status'] = 'open';
			}
		}
	}
	
	function acp_settings()
	{
		$this->ipsclass->parser->parse_smilies   = 1;
		$this->ipsclass->parser->parse_html      = 1;
		$this->ipsclass->parser->parse_bbcode    = 1;
		
		if ( $this->ipsclass->han_editor->method == 'rte' )
		{
			$message = $this->ipsclass->parser->pre_display_parse( $this->ipsclass->parser->pre_db_parse( $this->settings['win_message'] ) );
			$message = $this->ipsclass->parser->convert_ipb_html_to_html( $message );
		}
		else
		{
			$message = $this->ipsclass->parser->pre_edit_parse( $this->settings['win_message'] );
		}
		
		$html = "";
		
		$html .= $this->ipsclass->adskin->add_td_row(array(
															"<b>Send a Message?",
															$this->ipsclass->adskin->form_dropdown('send_pm',array(array(0,'Do not send a message'),array(1,'Send a PM'),array(2,'Send an email')),$this->settings['send_pm']),
													)	);
		
		$html .= $this->ipsclass->adskin->add_td_row(array(
															"<b>General Subject:</b>",
															$this->ipsclass->adskin->form_input('win_subject',$this->settings['win_subject']),
													)	);
		
		$html .= $this->ipsclass->adskin->add_td_row(array(
															"<b>General Message:</b><br />Tags:<br />{member_name} = Member Name of Winner",
															$this->ipsclass->han_editor->show_editor( $message, 'win_message' ),
													)	);
		
		return $html;
	}
	
	function acp_save_settings(&$input)
	{
		$this->ipsclass->parser->parse_smilies   = 1;
		$this->ipsclass->parser->parse_html      = 1;
		$this->ipsclass->parser->parse_bbcode    = 1;
		
		$save = array();
		$save['send_pm'] = min(max(intval($this->ipsclass->input['send_pm']),0),2);
		$save['win_subject'] = $this->ipsclass->input['win_subject'];
        $save['win_message'] = $this->ipsclass->han_editor->process_raw_post( 'win_message' );
		$save['win_message'] = $this->ipsclass->parser->pre_edit_parse( $this->ipsclass->parser->pre_db_parse( $save['win_message'] ) );
		
		$input['plugin_config'] = serialize($save);
	}
	
	function acp()
	{
		// Yes redirect again >_>
		$redirect = array(
								'list' => 'list_raffle',
								'edit' => 'edit_raffle',
								'type' => 'type_raffle',
								'prize' => 'prize_raffle',
								'save' => 'save_raffle',
								'delete' => 'delete_raffle',
								'tickets' => 'view_tickets',
								'previous' => 'old_raffle',
								'result' => 'view_result',
							);
		if(!$redirect[$this->ipsclass->input['action']])
		{
			$this->ipsclass->input['action'] = 'list';
		}
		
		$function = 'acp_'.$redirect[$this->ipsclass->input['action']];
		$this->$function();
	}
	
	function acp_list_raffle()
	{
		$trans = array();
		$trans['open'] = "Open";
		$trans['closed'] = "Closed";
		
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;action=list', 'Manage Raffles' );
		
		$this->ipsclass->adskin->td_header[] = array( "Name/Description"             , "" );
		$this->ipsclass->adskin->td_header[] = array( "Status/Tickets Available"     , "" );
		$this->ipsclass->adskin->td_header[] = array( "Time Starting/Ending"         , "" );
		$this->ipsclass->adskin->td_header[] = array( "Options"                      , "" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Lotteries");
		
		uasort($this->ipsclass->cache['ibm_raffle'],array($this,'order_end_time'));
		
		if(is_array($this->ipsclass->cache['ibm_raffle']) and count($this->ipsclass->cache['ibm_raffle']))
		{
			foreach($this->ipsclass->cache['ibm_raffle'] as $raffle)
			{
				$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																					"<b>".$raffle['r_name']."</b><br />".$raffle['r_description'],
																					"Status: ".$trans[$raffle['r_status']]."<br />Tickets: ".($raffle['stock_tickets'] < 0 ? "Infinite" : $this->ipsclass->do_number_format($raffle['stock_tickets'])),
																					"Starting: ".$this->ipsclass->get_date($raffle['start_time'],'LONG')."<br />Ending: ".$this->ipsclass->get_date($raffle['end_time'],'LONG'),
																					"<img id=\"menu_{$raffle['r_id']}\" src='{$this->ipsclass->vars['board_url']}/skin_acp/IPB2_Standard/images/filebrowser_action.gif' border='0' alt='Options' class='ipd' style='float:right'/>",
																			)	);
				
				$this->ipsclass->html .= "<script type=\"text/javascript\">
	menu_build_menu( \"menu_{$raffle['r_id']}\",
  new Array(
			img_item   + \" <a href='{$this->ipsclass->base_url}&{$this->ipsclass->form_code_js}&action=edit&raffle={$raffle['r_id']}'>Edit Raffle</a>\",
			img_item   + \" <a href='{$this->ipsclass->base_url}&{$this->ipsclass->form_code_js}&action=delete&raffle={$raffle['r_id']}'>Delete Raffle</a>\",
			img_item   + \" <a href='{$this->ipsclass->base_url}&{$this->ipsclass->form_code_js}&action=tickets&raffle={$raffle['r_id']}'>View Tickets</a>\"
      )     );
 </script>";
			}
		}
		else
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic("No active raffle made yet",'center');
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$raffle = array();
		$raffle['r_id'] = 0;
		$raffle['r_name'] = "New Raffle";
		$raffle['r_description'] = "";
		$raffle['r_prize_sets'] = 1;
		$raffle['r_status'] = 'open';
		$raffle['start_time'] = time();
		$raffle['end_time'] = time() + 604800;
		$raffle['continuous'] = 1;
		$raffle['r_price'] = 10;
		$raffle['stock_tickets'] = -1;
		$raffle['sell_back'] = 2;
		$raffle['create_time'] = time();
		$raffle['max_tickets'] = 0;
		$this->_acp_raffle_form($raffle);
		
		$this->ipsclass->admin->output();
	}
	
	function acp_prize_raffle()
	{
		$this->ipsclass->input['r_id'] = intval($this->ipsclass->input['r_id']);
		if($this->ipsclass->input['r_id'] != 0)
		{
			if(!is_array($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['r_id']]))
			{
				$this->ipsclass->admin->error("Cannot find raffle");
			}
			if($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['r_id']]['r_status'] == 'drawn')
			{
				$this->ipsclass->admin->error("The raffle has already been drawn");
			}
		}
		$this->ipsclass->input['r_prize_sets'] = intval($this->ipsclass->input['r_prize_sets']);
		if($this->ipsclass->input['r_prize_sets'] <= 0)
		{
			$this->ipsclass->input['r_prize_sets'] = 1;
		}
		
		$raffle = array();
		$raffle['r_id'] = $this->ipsclass->input['r_id'];
		$raffle['r_name'] = $this->ipsclass->input['r_name'];
		$raffle['r_description'] = $this->ipsclass->input['r_description'];
		$raffle['r_status'] = $this->ipsclass->input['r_status'];
		$raffle['r_prize_sets'] = $this->ipsclass->input['r_prize_sets'];
		$raffle['start_time'] = $this->ipsclass->input['start_time'];
		$raffle['end_time'] = $this->ipsclass->input['end_time'];
		$raffle['continuous'] = $this->ipsclass->input['continuous'];
		$raffle['r_price'] = $this->ipsclass->input['r_price'];
		$raffle['stock_tickets'] = $this->ipsclass->input['stock_tickets'];
		$raffle['sell_back'] = $this->ipsclass->input['sell_back'];
		$raffle['create_time'] = $this->ipsclass->input['create_time'];
		
		$this->ipsclass->html .= $this->_acp_start_form(array(
																	array('action','save'),
														),'theAdminForm',"onsubmit='return ValidateForm()'");
		
		$hidden = array();
		foreach($raffle as $k => $v)
		{
			$hidden[] = array($k,$v);
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->form_hidden($hidden);
		
		$this->ipsclass->adskin->td_header[] = array( "{none}" , "40%" );
		$this->ipsclass->adskin->td_header[] = array( "{none}" , "60%" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Set prizes");
		
		for($i = 0; $i < $this->ipsclass->input['r_prize_sets']; $i++)
		{
			$show = $i == 0 ? "Grand" : $this->ipsclass->numbers->ordinal_form($i);
			
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic($show." Prize", 'left', 'tablesubheader');
			
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Number of Winners for this Prize Set</b>",
																				  $this->ipsclass->adskin->form_simple_input("prizes[winner][".$i."]",$this->ipsclass->input['r_id'] == 0 ? 1 : $this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['r_id']]['prizes']['winner'][$i])
																		 )      );
																		 
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>".$this->ipsclass->vars['market_currency']." Prize</b>",
																				  $this->ipsclass->numbers->currency_format($this->ipsclass->adskin->form_simple_input("prizes[money][".$i."]",$this->ipsclass->input['r_id'] == 0 ? 0 : $this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['r_id']]['prizes']['money'][$i]))
																		 )      );
																		 
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Item Prizes</b>",
																				  $this->ipsclass->market_admin->compile_item_list("prizes[items][".$i."]",$this->ipsclass->input['r_id'] == 0 ? array() : $this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['r_id']]['prizes']['items'][$i],'item_table_'.$i,'item_id_'.$i,'quan_id_'.$i)
																		 )      );
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_form("Save Prizes");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->admin->output();
	}
	
	function acp_edit_raffle()
	{
		$this->ipsclass->input['raffle'] = intval($this->ipsclass->input['raffle']);
		if(!is_array($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]))
		{
			$this->ipsclass->admin->error("Cannot find raffle");
		}
		if($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['r_status'] == 'drawn')
		{
			$this->ipsclass->admin->error("The raffle has already been drawn");
		}
		
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;action=starter', 'Manage Lotteries' );
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;action=starter&amp;action=edit&amp;raffle='.$this->ipsclass->input['l_id'], 'Edit Lottery Information' );
		
		$this->_acp_raffle_form($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]);
		
		$this->ipsclass->admin->output();
	}
	
	function _acp_raffle_form($raffle = array())
	{
		$date = $this->ipsclass->unixstamp_to_human($raffle['start_time']);
		$start = sprintf("%02d/%02d/%04d %02d:%02d", $date['month'], $date['day'], $date['year'], $date['hour'] , $date['minute'] );
		$date = $this->ipsclass->unixstamp_to_human($raffle['end_time']);
		$end = sprintf("%02d/%02d/%04d %02d:%02d", $date['month'], $date['day'], $date['year'], $date['hour'] , $date['minute'] );
		
		if ( $this->ipsclass->han_editor->method == 'rte' )
		{
			$raffle['r_description'] = $this->ipsclass->parser->pre_display_parse( $this->ipsclass->parser->pre_db_parse( $raffle['r_description'] ) );
			$raffle['r_description'] = $this->ipsclass->parser->convert_ipb_html_to_html( $raffle['r_description'] );
		}
		else
		{
			$raffle['r_description'] = $this->ipsclass->parser->pre_edit_parse( $raffle['r_description'] );
		}
        
		$this->ipsclass->html .= $this->_acp_start_form(array(
																	array('action','prize'),
														),'theAdminForm',"onsubmit='return ValidateForm()'");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->form_hidden(array(array('r_id',$raffle['r_id'])));
		
		if($raffle['r_id'])
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->form_hidden(array(array('create_time',time()-time()%60)));
		}
		
		$this->ipsclass->adskin->td_header[] = array( "{none}" , "40%" );
		$this->ipsclass->adskin->td_header[] = array( "{none}" , "60%" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table($raffle['r_id'] ? "Edit a Raffle" : "Add a Raffle");
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Name</b><br />The name of the raffle.",
																			  $this->ipsclass->adskin->form_input("r_name",$raffle['r_name'])
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic("<b>Description</b>: The description for the quiz.<br />".$this->ipsclass->han_editor->show_editor( $raffle['l_description'], 'l_description' ), 'left', 'tablerow1');
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Status of the raffle</b><br />When the raffle is closed, no one can buy tickets but it still will be drawn at end time.",
																			  $this->ipsclass->adskin->form_dropdown("r_status",array(array('open',"Open"),array('closed',"Closed")),$raffle['r_status'])
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Number of Prize sets</b><br />The number of set prizes for the raffle. This does not mean the number of winners",
																			  $this->ipsclass->adskin->form_simple_input("r_prize_sets",$raffle['r_prize_sets'])
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Starting time of this raffle</b><br />Input Format (24-hour time): MM/DD/YYYY HH:MM<br /><i>The raffle is automatically closed until the starting time.</i>",
																			  $this->ipsclass->adskin->form_input("start_time",$start)
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Ending time of this raffle</b><br />Input Format (24-hour time): MM/DD/YYYY HH:MM<br /><i>The raffle is automatically closed until the starting time.</i>",
																			  $this->ipsclass->adskin->form_input("end_time",$end)
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Is this raffle continuous?</b>",
																			  $this->ipsclass->adskin->form_dropdown("continuous",array(array(0,"Not continueous"),array(1,"Consecutively Continuous"),array(2,"Continuous with delay")),$raffle['continuous'])
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Ticket Price</b>",
																			  $this->ipsclass->numbers->currency_format($this->ipsclass->adskin->form_simple_input("r_price",$raffle['r_price']))
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Ticket Stock</b><br />Input -1 for infinite tickets",
																			  $this->ipsclass->adskin->form_simple_input("stock_tickets",$raffle['stock_tickets'])." tickets"
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Maximum tickets someone can hold</b><br />0 for unlimited",
																			  $this->ipsclass->adskin->form_simple_input("max_tickets",$raffle['max_tickets'])
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Allow sell tickets back</b><br />This will refund the user's money back",
																			  $this->ipsclass->adskin->form_dropdown("sell_back",array(array(0,"No Sell Back"),array(1,"Sell ticket back, not add ticket back to stock"),array(2,"Sell ticket back, add ticket back to stock")),$raffle['sell_back'])
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_form("Edit Prizes");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
	}
	
	function acp_save_raffle()
	{
		$this->ipsclass->input['r_id'] = intval($this->ipsclass->input['r_id']);
		if($this->ipsclass->input['r_id'] != 0 && !is_array($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['r_id']]))
		{
			$this->ipsclass->admin->error("Cannot find lottery");
		}
		
		list($date, $time) = explode(" ",$this->ipsclass->input['start_time']);
		list($month,$day,$year) = explode("/",$date);
		list($hour,$minute) = explode(":",$time);
		if($this->ipsclass->market_class->check_24_time($month, $day, $year, $hour, $minute))
		{
			$this->ipsclass->input['start_time'] = $this->ipsclass->convert_local_date_to_unix( array( 'month'  => intval($month),
																									   'day'    => intval($day),
																									   'year'   => intval($year),
																									   'hour'   => intval($hour),
																									   'minute' => intval($minute) ) );
		}
		else
		{
			$this->ipsclass->admin->error("Bad starting time, the date/time must be in correct format and a valid date/time");
		}
		list($date, $time) = explode(" ",$this->ipsclass->input['end_time']);
		list($month,$day,$year) = explode("/",$date);
		list($hour,$minute) = explode(":",$time);
		if($this->ipsclass->market_class->check_24_time($month, $day, $year, $hour, $minute))
		{
			$this->ipsclass->input['end_time'] = $this->ipsclass->convert_local_date_to_unix( array( 'month'  => intval($month),
																									 'day'    => intval($day),
																									 'year'   => intval($year),
																									 'hour'   => intval($hour),
																									 'minute' => intval($minute) ) );
		}
		else
		{
			$this->ipsclass->admin->error("Bad ending time, the date/time must be in correct format and a valid date/time");
		}
		
		$this->ipsclass->input['r_prize_sets'] = intval($this->ipsclass->input['r_prize_sets']);
		$prizes = array();
		for($i = 0; $i < $this->ipsclass->input['r_prize_sets']; $i++)
		{
			$k = $i == 0 ? "" : $i;
			$prizes['winner'][$i] = intval($this->ipsclass->input['prizes']['winner'][$k]);
			$prizes['money'][$i] = $this->ipsclass->numbers->parse_input_number($this->ipsclass->input['prizes']['money'][$k],'int');
			$prizes['items'][$i] = $this->ipsclass->market_admin->parse_input_item_list(array('prizes','items',$k));
		}
		
		$raffle = array();
		$raffle['r_name'] = $this->ipsclass->input['r_name'];
		$raffle['r_description'] = $this->ipsclass->parser->pre_display_parse( $this->ipsclass->parser->pre_db_parse( $this->ipsclass->han_editor->process_raw_post( 'r_description' ) ) );
		$raffle['r_status'] = $this->ipsclass->input['r_status'];
		$raffle['r_prize_sets'] = $this->ipsclass->input['r_prize_sets'];
		$raffle['start_time'] = $this->ipsclass->input['start_time'];
		$raffle['end_time'] = $this->ipsclass->input['end_time'];
		$raffle['continuous'] = min(max($this->ipsclass->input['continuous'],0),2);
		$raffle['r_price'] = $this->ipsclass->numbers->parse_input_number($this->ipsclass->input['r_price'],'int');
		$raffle['stock_tickets'] = intval($this->ipsclass->input['stock_tickets']);
		$raffle['max_tickets'] = intval($this->ipsclass->input['max_tickets']);
		$raffle['sell_back'] = min(max($this->ipsclass->input['sell_back'],0),2);
		$raffle['prizes'] = serialize($prizes);
		
		if($this->ipsclass->input['r_id'] == 0)
		{
			$raffle['create_time'] = $this->ipsclass->input['create_time'] ? $this->ipsclass->input['create_time'] : max(time(),$this->ipsclass->input['start_time']);
			
			$this->ipsclass->DB->do_insert('market_raffle',$raffle);
		
			$this->ipsclass->admin->save_log("ibMarket: Raffle Added(".$this->ipsclass->input['r_name'].")");
		}
		else
		{
			$this->ipsclass->DB->do_update('market_raffle',$raffle,"r_id=".$this->ipsclass->input['r_id']);
			
			$this->ipsclass->admin->save_log("ibMarket: Raffle Editted(".$this->ipsclass->input['r_name'].")");
		}
		
		$this->raffle_cache();
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js,"Raffle, ".$this->ipsclass->input['r_name'].", saved...");
	}
	
	function acp_delete_raffle()
	{
		$this->ipsclass->input['r_id'] = intval($this->ipsclass->input['raffle']);
		if(!is_array($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]))
		{
			$this->ipsclass->admin->error("Cannot find raffle");
		}
		
		$this->ipsclass->DB->build_and_exec_query(array('delete'=>'market_raffle','where'=>"r_id=".$this->ipsclass->input['r_id']));
		$this->ipsclass->DB->build_and_exec_query(array('delete'=>'market_raffle_tickets','where'=>"raffle_id=".$this->ipsclass->input['r_id']));
		
		$this->ipsclass->admin->save_log("ibMarket: Raffle Deleted(".$this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['r_id']]['r_name'].")");
		
		$this->raffle_cache();
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js,"Raffle deleted...");
	}
	
	function acp_view_tickets()
	{
		$this->ipsclass->input['raffle'] = intval($this->ipsclass->input['raffle']);
		if(!is_array($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]))
		{
			$this->ipsclass->admin->error("Cannot find raffle");
		}
		
		$LIMIT = 25;
		$this->ipsclass->input['st'] = intval($this->ipsclass->input['st']);
		
		$count = $this->ipsclass->DB->build_and_exec_query(array('select'=>'COUNT(*) as count','from'=>'market_raffle_tickets','where'=>"raffle_id=".$this->ipsclass->input['raffle']));
		$page = $this->ipsclass->adskin->build_pagelinks(	array(	'TOTAL_POSS'   => $count['count'],
																	'PER_PAGE'     => $LIMIT,
																	'USE_ST'       => 'st',
																	'CUR_ST_VAL'   => $this->ipsclass->input['st'],
																	'L_SINGLE'     => "Single Page",
																	'BASE_URL'     => $this->ipsclass->base_url."&amp;".$this->ipsclass->form_code."&amp;action=ticket&amp;raffle=".$this->ipsclass->input['raffle']
															)	);

		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;action=list', 'Manage Lotteries' );
		$this->ipsclass->admin->nav[] 		= array( ''                                           , 'View Tickets' );
		$this->ipsclass->admin->nav[] 		= array( ''                                           , $this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['l_name'] );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_standalone_row($page,"left");
		
		$this->ipsclass->html .= "<br />";
		
		$this->ipsclass->adskin->td_header[] = array( "Member"        , "" );
		$this->ipsclass->adskin->td_header[] = array( "Date Bought"   , "" );
		$this->ipsclass->adskin->td_header[] = array( "IP Address"    , "" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Tickets");
		
		$this->ipsclass->DB->build_query(array(
												'select' => 't.*',
												'from' => array('market_raffle_tickets'=>'t'),
												'add_join' => array(
																		array(
																				'select' => 'm.members_display_name',
																				'from' => array('members'=>'m'),
																				'where' => 'm.id=t.member_id',
																				'type' => 'left',
																			),
																	),
												'where' => "t.raffle_id=".$this->ipsclass->input['raffle'],
												'order' => 't.time_bought DESC',
												'limit' => array($this->ipsclass->input['st'],$LIMIT),
										)	);
		$this->ipsclass->DB->exec_query();
		while($ticket = $this->ipsclass->DB->fetch_row())
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																				$ticket['members_display_name'],
																				$this->ipsclass->get_date($ticket['time_bought'],'LONG'),
																				$ticket['ip_address'],
																		)	);
		}
		
		if($this->ipsclass->DB->get_num_rows() == 0)
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic("No tickets bought yet",'center');
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_standalone_row($page,"left");
		
		$this->ipsclass->admin->output();
	}
	
	function acp_old_raffle()
	{
		$this->ipsclass->input['st'] = intval($this->ipsclass->input['st']);
		$LIMIT = 25;
		
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;action=previous', 'Previous Raffles' );
		
		$count = $this->ipsclass->DB->build_and_exec_query(array('select'=>'COUNT(*) as count','from'=>'market_raffle','where'=>"r_status='drawn'"));
		$page = $this->ipsclass->adskin->build_pagelinks(	array(	'TOTAL_POSS'   => $count['count'],
																	'PER_PAGE'     => $LIMIT,
																	'USE_ST'       => 'st',
																	'CUR_ST_VAL'   => $this->ipsclass->input['st'],
																	'L_SINGLE'     => "Single Page",
																	'BASE_URL'     => $this->ipsclass->base_url."&amp;".$this->ipsclass->form_code."&amp;action=previous"
															)	);

		$this->ipsclass->html .= $this->ipsclass->adskin->add_standalone_row($page,"left");
		
		$this->ipsclass->html .= "<br />";
		
		$this->ipsclass->adskin->td_header[] = array( "Name/Description" , "" );
		$this->ipsclass->adskin->td_header[] = array( "Ended"            , "" );
		$this->ipsclass->adskin->td_header[] = array( "Options"          , "" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Raffles");
		
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_raffle','where'=>"r_status='drawn'",'limit'=>array($this->ipsclass->input['st'],$LIMIT)));
		$this->ipsclass->DB->exec_query();
		while($raffle = $this->ipsclass->DB->fetch_row())
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																				"<b>".$raffle['r_name']."</b><br />".$raffle['r_description'],
																				"Ending: ".$this->ipsclass->get_date($raffle['end_time'],'LONG'),
																				"<img id=\"menu_{$raffle['l_id']}\" src='{$this->ipsclass->vars['board_url']}/skin_acp/IPB2_Standard/images/filebrowser_action.gif' border='0' alt='Options' class='ipd' style='float:right'/>",
																		)	);
			
			$this->ipsclass->html .= "<script type=\"text/javascript\">
	menu_build_menu( \"menu_{$raffle['r_id']}\",
  new Array(
			img_item   + \" <a href='{$this->ipsclass->base_url}&{$this->ipsclass->form_code_js}&action=result&raffle={$raffle['r_id']}'>View Tickets</a>\"
      )     );
</script>";
		}
		
		if($this->ipsclass->DB->get_num_rows() == 0)
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic("No active raffles made yet",'center');
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_standalone_row($page,"left");
		
		$this->ipsclass->admin->output();
	}
	
	function acp_view_result()
	{
		$this->ipsclass->input['raffle'] = intval($this->ipsclass->input['raffle']);
		$raffle = $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'market_raffle','where'=>"r_id=".$this->ipsclass->input['raffle']));
		$raffle['prizes'] = unserialize($raffle['prizes']);
		if(!$raffle)
		{
			$this->ipsclass->admin->error("Cannot find raffle");
		}
		
		$LIMIT = 25;
		$this->ipsclass->input['st'] = intval($this->ipsclass->input['st']);
		
		$count = $this->ipsclass->DB->build_and_exec_query(array('select'=>'COUNT(*) as count','from'=>'market_raffle_tickets','where'=>"raffle_id=".$this->ipsclass->input['raffle']));
		$page = $this->ipsclass->adskin->build_pagelinks(	array(	'TOTAL_POSS'   => $count['count'],
																	'PER_PAGE'     => $LIMIT,
																	'USE_ST'       => 'st',
																	'CUR_ST_VAL'   => $this->ipsclass->input['st'],
																	'L_SINGLE'     => "Single Page",
																	'BASE_URL'     => $this->ipsclass->base_url."&amp;".$this->ipsclass->form_code."&amp;action=ticket&amp;raffle=".$this->ipsclass->input['raffle']
															)	);

		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;action=list', 'Manage Lotteries' );
		$this->ipsclass->admin->nav[] 		= array( ''                                           , 'View Tickets'     );
		$this->ipsclass->admin->nav[] 		= array( ''                                           , $raffle['r_name'] );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_standalone_row($page,"left");
		
		$this->ipsclass->html .= "<br />";
		
		$this->ipsclass->adskin->td_header[] = array( "Member"        , "" );
		$this->ipsclass->adskin->td_header[] = array( "Date Bought"   , "" );
		$this->ipsclass->adskin->td_header[] = array( "IP Address"    , "" );
		$this->ipsclass->adskin->td_header[] = array( "Prize Won"     , "" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Tickets");
		
		$this->ipsclass->DB->build_query(array(
												'select' => 't.*',
												'from' => array('market_raffle_tickets'=>'t'),
												'add_join' => array(
																		array(
																				'select' => 'm.members_display_name',
																				'from' => array('members'=>'m'),
																				'where' => 'm.id=t.member_id',
																				'type' => 'left',
																			),
																	),
												'where' => "t.raffle_id=".$this->ipsclass->input['raffle'],
												'order' => 't.time_bought DESC',
												'limit' => array($this->ipsclass->input['st'],$LIMIT),
										)	);
		$this->ipsclass->DB->exec_query();
		while($ticket = $this->ipsclass->DB->fetch_row())
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																				$ticket['members_display_name'],
																				$this->ipsclass->get_date($ticket['time_bought'],'LONG'),
																				$ticket['ip_address'],
																				$ticket['t_prize'] == -1 ? ($ticket['t_prize'] == 0 ? "Grand" : $this->ipsclass->numbers->ordinal_form($ticket['t_prize'])).' prize' : "- NONE -",
																		)	);
		}
		
		if($this->ipsclass->DB->get_num_rows() == 0)
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic("No tickets bought yet",'center');
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_standalone_row($page,"left");
		
		$this->ipsclass->admin->output();
	}
	
	function acp_install()
	{
		$this->ipsclass->DB->load_cache_file(ROOT_PATH.'sources/market/sql/'.$this->ipsclass->vars['sql_driver'].'_plugin_queries.php','sql_plugin_queries');
		
		$this->ipsclass->DB->build_query_from_cache('table_raffle',array(),'sql_plugin_queries');
		$this->ipsclass->DB->exec_query();
		$this->ipsclass->DB->build_query_from_cache('table_raffle_tickets',array(),'sql_plugin_queries');
		$this->ipsclass->DB->exec_query();
	}
	
	function acp_uninstall()
	{
		$this->ipsclass->DB->sql_drop_table( 'market_raffle' );
		$this->ipsclass->DB->sql_drop_table( 'market_raffle_tickets' );
	}
	
	function run()
	{
		$this->ipsclass->load_template('skin_market_plugin');
		$this->ipsclass->load_language('lang_market_plugin');
		
		$this->ipsclass->market_class->title[] = array($this->plugin['name'],'market_'.$this->plugin['link']);
		if(in_array($this->ipsclass->member['mgroup'],$this->plugin['use_permission']))
		{
			$this->ipsclass->market_class->menu[] = array(
															"<b><a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}'>".$this->ipsclass->lang['raffle_open_raffle']."</a></b>",
															"<b><a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}&amp;do=finished'>".$this->ipsclass->lang['raffle_prev_raffle']."</a></b>",
															"<b><a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}&amp;do=manage'>".$this->ipsclass->lang['raffle_check_tickets']."</a></b>",
															"<b><a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}&amp;do=check'>".$this->ipsclass->lang['raffle_old_tickets']."</a></b>",
														);
			
			$do_redirect = array(
									'list' => 'list_raffles',
									'ticket' => 'ticket_form',
									'buy' => 'buy_ticket',
									'prize' => 'view_prizes',
									'manage' => 'manage_tickets',
									'check' => 'check_tickets',
									'sell' => 'sell_back_ticket',
									'finished' => 'finished_raffles',
								  );
			
			if(!isset($do_redirect[$this->ipsclass->input['do']]))
			{
				$this->ipsclass->input['do'] = 'list';
			}
		}
		else
		{
			$this->ipsclass->market_class->menu[] = array(
															"<b><a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}'>".$this->ipsclass->lang['raffle_open_raffle']."</a></b>",
															"<b><a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}&amp;do=drawn'>".$this->ipsclass->lang['raffle_prev_raffle']."</a></b>",
														);
			
			$do_redirect = array(
									'list' => 'list_lotteries',
									'prize' => 'view_prizes',
									'drawn' => 'drawn_lotteries',
								  );
			
			if(!isset($do_redirect[$this->ipsclass->input['do']]))
			{
				$this->ipsclass->input['do'] = 'list';
			}
		}
		
		$func = 'run_'.$do_redirect[$this->ipsclass->input['do']];
		$this->$func();
	}
	
	function run_list_raffles()
	{
		$this->ipsclass->subtitle = $this->ipsclass->lang['raffle_open_raffle'];
		$this->ipsclass->nav = array("<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}'>".$this->plugin['name']."</a>","<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}'>".$this->ipsclass->lang['lottery_open_lottery']."</a>");
		
		$raffles = array();
		foreach($this->ipsclass->cache['ibm_raffle'] as $raffle)
		{
			$raffle['tickets'] = $raffle['stock_tickets'] < 0 ? $this->ipsclass->lang['infinite'] : $this->ipsclass->numbers->do_number_format($raffle['stock_tickets']);
			$raffle['drawing'] = $this->ipsclass->get_date($raffle['end_time'],'LONG');
			$raffle['price'] = $this->ipsclass->numbers->format_currency($raffle['r_price']);
			
			$raffles[] = $raffle;
		}
		
		usort($raffles,array(&$this,'order_end_time'));
		
		$this->ipsclass->output .= $this->ipsclass->compiled_templates['skin_market_plugin']->raffle_main_page($raffles);
	}
	
	function order_end_time($a,$b)
	{
		return $a['end_time'] < $b['end_time'] ? -1 : ($a['end_time'] > $b['end_time'] ? 1 : 0);
	}
	
	function run_ticket_form()
	{
		if(!is_array($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]) || $this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['r_status'] == 'closed')
		{
			$this->ipsclass->boink_it($this->ipsclass->market_class->base_url."plugin=".$this->plugin['link']);
		}
		
		if($this->ipsclass->numbers->compare($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['stock_tickets'],0) == 0 )
		{
			$this->ipsclass->Error(array('MSG'=>'raffle_no_tickets_left'));
		}
		
		$this->ipsclass->lang['raffle_ticket_pricing'] = sprintf($this->ipsclass->lang['raffle_ticket_pricing'],$this->ipsclass->numbers->format_currency($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['r_price']));
		$this->ipsclass->lang['raffle_ticket_left'] = sprintf($this->ipsclass->lang['raffle_ticket_left'],$this->ipsclass->do_number_format($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['stock_tickets']));
		
		$this->ipsclass->output .= $this->ipsclass->compiled_templates['skin_market_plugin']->raffle_buy_ticket();
	}
	
	function run_buy_ticket()
	{
		if(!is_array($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]) || $this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['r_status'] == 'closed')
		{
			$this->ipsclass->boink_it($this->ipsclass->market_class->base_url."plugin=".$this->plugin['link']);
		}
		
		$this->ipsclass->input['num_tickets'] = $this->ipsclass->numbers->parse_input_number($this->ipsclass->input['num_tickets'],'int');
		if($this->ipsclass->numbers->compare($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['stock_tickets'],0) >= 0 && $this->ipsclass->numbers->compare($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['stock_tickets'],$this->ipsclass->input['num_tickets']) < 0)
		{
			$this->ipsclass->input['num_tickets'] = $this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['stock_tickets'];
			if($this->ipsclass->numbers->compare($this->ipsclass->input['num_tickets'],0) == 0)
			{
				$this->ipsclass->Error(array('MSG'=>'raffle_no_tickets_left'));
			}
		}
		
		if($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['max_tickets'])
		{
			$count = $this->ipsclass->DB->build_and_execy_query(array('select'=>'COUNT(*) as count','from'=>'market_raffle_tickets','where'=>"member_id=".$this->ipsclass->member['id']." AND raffle_id=".$this->ipsclass->input['raffle']));
			if($this->ipsclass->numbers->compare($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['max_tickets'],$this->ipsclass->numbers->add($count,$this->ipsclass->input['num_tickets'])) < 0)
			{
				$this->ipsclass->input['num_tickets'] = $this->ipsclass->numbers->subtract($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['max_tickets'],$count);
				if($this->ipsclass->numbers->compare($this->ipsclass->input['num_tickets'], 0) <= 0)
				{
					$this->ipsclass->Error(array('MSG'=>'raffle_too_many_tickets'));
				}
			}
		}
		
		$totalPrice = $this->ipsclass->numbers->multiply($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['r_price'],$this->ipsclass->input['num_tickets']);
		if($this->ipsclass->numbers->compare($this->ipsclass->member[$this->ipsclass->vars['market_members_field']],$totalPrice) < 0)
		{
			$this->ipsclass->Error(array('MSG'=>'raffle_not_enough_money'));
		}
		
		$time = time();
		for($i = 0; $i < $this->ipsclass->input['num_tickets']; $i++)
		{
			$ticket = array(
								'member_id' => $this->ipsclass->member['id'],
								'raffle_id' => $this->ipsclass->input['raffle'],
								'price_bought' => $this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['r_price'],
								'time_bought' => $time,
								'checked' => 0,
								't_prize' => -1,
								'ip_address' => $this->ipsclass->ip_address,
							);
			$this->ipsclass->DB->do_insert('market_raffle_tickets',$ticket);
		}
		
		$this->ipsclass->DB->do_update('members',array(
														$this->ipsclass->vars['market_members_field'] => $this->ipsclass->numbers->subtract($this->ipsclass->member[$this->ipsclass->vars['market_members_field']],$totalPrice),
				),"id=".$this->ipsclass->member['id']);
		if($this->ipsclass->numbers->compare($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['stock_tickets'],0) > 0)
		{
			$this->ipsclass->DB->do_update('market_raffle',array(
																		'stock_tickets' => $this->ipsclass->numbers->subtract($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['stock_tickets'],$this->ipsclass->input['num_tickets']),
						),"r_id=".$this->ipsclass->input['raffle']);
			$this->raffle_cache();
		}
		
		$this->ipsclass->market_class->redirect('raffle_ticket_bought',"plugin=".$this->ipsclass->input['plugin']);
	}
	
	function run_manage_tickets()
	{
		$this->ipsclass->subtitle = $this->ipsclass->lang['raffle_manage_tickets'];
		$this->ipsclass->nav = array("<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}'>".$this->plugin['name']."</a>","<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}&amp;do=manage'>".$this->ipsclass->lang['raffle_manage_tickets']."</a>");
		
		$tickets = array();
		$this->ipsclass->DB->build_query(array('select'=>'COUNT(*) as num_tickets, t_id, raffle_id, time_bought','from'=>'market_raffle_tickets','where'=>"checked=0 AND member_id=".$this->ipsclass->member['id'],'group'=>"raffle_id, time_bought"));
		$this->ipsclass->DB->exec_query();
		while($ticket = $this->ipsclass->DB->fetch_row())
		{
			$ticket['time_bought'] = $this->ipsclass->get_date($ticket['time_bought'],'LONG');
			$ticket['num_tickets'] = $this->ipsclass->do_number_format($ticket['num_tickets']);
			$tickets[] = $ticket;
		}
		foreach($this->ipsclass->cache['ibm_raffle'] as $r_id => $raffle)
		{
			$this->ipsclass->cache['ibm_raffle'][$r_id]['drawing'] = $this->ipsclass->get_date($raffle['end_time'],'LONG');
		}
		
		usort($tickets,array(&$this,'order_active_tickets'));
		
		$this->ipsclass->output .= $this->ipsclass->compiled_templates['skin_market_plugin']->raffle_manage_tickets($tickets);
	}
	
	function order_active_tickets($a,$b)
	{
		if($a['raffle_id'] == $b['raffle_id'])
		{
			if($a['time_bought'] < $b['time_bought'])
			{
				return -1;
			}
			else
			{
				return 1;
			}
		}
		else
		{
			if($this->ipsclass->cache['ibm_raffle'][$a['raffle_id']]['end_time'] == $this->ipsclass->cache['ibm_raffle'][$b['raffle_id']]['end_time'])
			{
				if($a['raffle_id'] < $b['raffle_id'])
				{
					return -1;
				}
				else
				{
					return 1;
				}
			}
			elseif($this->ipsclass->cache['ibm_raffle'][$a['raffle_id']]['end_time'] < $this->ipsclass->cache['ibm_raffle'][$b['raffle_id']]['end_time'])
			{
				return -1;
			}
			else
			{
				return 1;
			}
		}
	}
	
	function run_sell_back_ticket()
	{
		$this->ipsclass->input['ticket'] = intval($this->ipsclass->input['ticket']);
		
		$ticket = $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'market_raffle_tickets','where'=>"t_id=".$this->ipsclass->input['ticket']));
		
		if(!$ticket || $this->ipsclass->input['raffle'] != $ticket['raffle_id'] || $this->ipsclass->member['id'] != $ticket['member_id'])
		{
			$this->ipsclass->Error(array('MSG'=>'raffle_invalid_ticket'));
		}
		
		if($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['sell_back'] == 0 || $this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['r_status'] == 'drawn')
		{
			$this->ipsclass->Error(array('MSG'=>'raffle_cant_sell_back'));
		}
		
		$count = $this->ipsclass->DB->build_and_exec_query(array('select'=>'COUNT(*) as count','from'=>'market_raffle_tickets','where'=>"t_id=".$this->ipsclass->input['ticket']));
		
		$this->ipsclass->DB->do_update('members',array(
														$this->ipsclass->vars['market_members_field'] => $this->ipsclass->numbers->add($this->ipsclass->member[$this->ipsclass->vars['market_members_field']],$this->ipsclass->numbers->multiply($ticket['price_bought'],$count['count'])),
				),"id=".$this->ipsclass->member['id']);
		if($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['sell_back'] == 2)
		{
			$this->ipsclass->DB->do_update('market_raffle',array(
																		'stock_tickets' => $this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['lottery']]['stock_tickets']+$count['count'],
						),"r_id=".$this->ipsclass->input['raffle']);
			$this->raffle_cache();
		}
		$this->ipsclass->DB->do_delete('market_raffle_tickets',"t_id=".$this->ipsclass->input['ticket']);
		
		$this->ipsclass->market_class->redirect('raffle_ticket_resold',"plugin=".$this->ipsclass->input['plugin']."&do=manage");
	}
	
	function run_check_tickets()
	{
		$this->ipsclass->input['st'] = intval($this->ipsclass->input['st']);
		
		$this->ipsclass->subtitle = $this->ipsclass->lang['raffle_old_tickets'];
		$this->ipsclass->nav = array("<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}'>".$this->plugin['name']."</a>","<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}&amp;do=check'>".$this->ipsclass->lang['raffle_old_tickets']."</a>");
		
		$LIMIT = 25;
		$total = $this->ipsclass->DB->build_and_exec_query(array('select'=>'COUNT(*) as total','from'=>'market_raffle_tickets','where'=>"checked=1 AND member_id=".$this->ipsclass->member['id'],'group'=>'raffle_id,t_prize'));
		$page_links = $this->ipsclass->build_pagelinks(	array(	'TOTAL_POSS'   => $total['total'],
																'PER_PAGE'     => $LIMIT,
																'CUR_ST_VAL'   => $this->ipsclass->input['st'],
																'L_SINGLE'     => $this->ipsclass->compiled_templates['skin_global']->pagination_compile($this->ipsclass->compiled_templates['skin_global']->pagination_make_jump(),"","",$this->ipsclass->compiled_templates['skin_global']->pagination_current_page(1),"","",1,$LIMIT,$this->ipsclass->market_class->base_url."plugin=".$this->ipsclass->input['plugin']."&amp;do=check",0,'st'),
																'BASE_URL'     => $this->ipsclass->market_class->base_url."plugin=".$this->ipsclass->input['plugin']."&amp;do=check",
																'USE_ST'       => 'st',
														)	);
		
		$get_raffles = array();
		$tickets = array();
		$this->ipsclass->DB->build_query(array('select'=>'*, COUNT(*) as count','from'=>'market_raffle_tickets','where'=>"checked=1 AND member_id=".$this->ipsclass->member['id'],'group'=>'raffle_id,t_prize','order'=>"raffle_id ASC, t_prize DESC",'limit'=>array($this->ipsclass->input['st'],$LIMIT)));
		$this->ipsclass->DB->exec_query();
		while($ticket = $this->ipsclass->DB->fetch_row())
		{
			$ticket['count'] = $this->ipsclass->do_number_format($ticket['count'],'LONG');
			$get_raffles[$ticket['raffle_id']][] = $ticket['t_id'];
			$tickets[$ticket['t_id']] = $ticket;
		}
		
		if(count($get_raffles))
		{
			$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_raffle','where'=>"r_id IN (".implode(", ",array_keys($get_raffles)).")",'order'=>"r_id DESC"));
			$q = $this->ipsclass->DB->exec_query();
			while($raffle = $this->ipsclass->DB->fetch_row($q))
			{
				$raffle['prizes'] = unserialize($raffle['prizes']);
				$end_time = $this->ipsclass->get_date($raffle['end_time'],'LONG');
				
				foreach($get_raffles[$raffle['l_id']] as $t_id)
				{
					$tickets[$t_id]['time_drawn'] = $end_time;
					$tickets[$t_id]['r_name'] = $raffle['r_name'];
					$tickets[$t_id]['r_desc'] = $raffle['r_desc'];
					$tickets[$t_id]['won'] = $tickets[$t_id]['t_prize'] !== -1 ? sprintf($this->ipsclass->lang['raffle_ordinal_prize'],$tickets[$t_id]['t_prize'] == 0 ? $this->ipsclass->lang['raffle_grand'] : $this->ipsclass->numbers->ordinal_form($tickets[$t_id]['t_prize'])) : $this->ipsclass->lang['raffle_no_win'];
				}
			}
		}
		
		$this->ipsclass->output .= $this->ipsclass->compiled_templates['skin_market_plugin']->raffle_old_tickets($tickets,$page_links);
	}
	
	function run_view_prizes()
	{
		if(!is_array($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]))
		{
			$this->ipsclass->input['raffle'] = intval($this->ipsclass->input['raffle']);
			$this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']] = $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'market_raffle','where'=>"r_id=".$this->ipsclass->input['raffle']));
			$this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['prizes'] = unserialize($this->ipsclass->cache['ibm_lottery'][$this->ipsclass->input['raffle']]['prizes']);
			if(!$this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']])
			{
				$this->ipsclass->boink_it($this->ipsclass->market_class->base_url."plugin=".$this->plugin['link']);
			}
		}
		
		$this->ipsclass->subtitle = $this->ipsclass->lang['raffle_view_prizes'];
		$this->ipsclass->nav = array("<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}'>".$this->plugin['name']."</a>",$this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['r_name'],$this->ipsclass->lang['raffle_view_prizes']);
		
		$total = $this->ipsclass->DB->build_and_exec_query(array('select'=>'COUNT(*) as total','from'=>'market_raffle_tickets','where'=>"raffle_id=".$this->ipsclass->input['raffle']));
		
		$this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['drawing'] = $this->ipsclass->get_date($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['end_time'],'LONG');
		$this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['tickets'] = $this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['stock_tickets'] < 0 ? $this->ipsclass->lang['infinite'] : $this->ipsclass->numbers->do_number_format($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['stock_tickets']);
		$this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['total_tickets'] = $this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['stock_tickets'] < 0 ? $this->ipsclass->lang['infinite'] : $this->ipsclass->numbers->do_number_format($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['stock_tickets'] + $total['total']);
		$this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['sold'] = $this->ipsclass->numbers->do_number_format($total['total']);
		$this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['price'] = $this->ipsclass->numbers->format_currency($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['r_price']);
		
		foreach($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['prizes']['winner'] as $k => $winner)
		{
			$items = array();
			if(is_array($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['prizes']['items'][$k]) && count($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['items'][$k]))
			{
				foreach($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['prizes']['items'][$k] as $i_id => $quan)
				{
					if($quan == 1)
					{
						$items[] = $this->ipsclass->cache['market_items'][$i_id]['item_name'];
					}
					else
					{
						$items[] = $this->ipsclass->cache['market_items'][$i_id]['item_name'];
					}
				}
			}
			else
			{
				$items[] = $this->ipsclass->lang['none'];
			}
			
			$this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['prizes']['ordinal'][$k] = sprintf($this->ipsclass->lang['raffle_ordinal_prize'],$k == 0 ? $this->ipsclass->lang['raffle_grand'] : $this->ipsclass->numbers->ordinal_form($k));
			$this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['prizes']['winner'][$k] = $this->ipsclass->do_number_format($winner);
			$this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['prizes']['money'][$k] = $this->ipsclass->numbers->format_currency($this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['prizes']['money'][$k]);
			$this->ipsclass->cache['ibm_raffle'][$this->ipsclass->input['raffle']]['prizes']['items'][$k] = implode(", ", $items);
		}
		
		$this->ipsclass->output .= $this->ipsclass->compiled_templates['skin_market_plugin']->raffle_view_prizes();
	}
	
	function run_finished_raffles()
	{
		$this->ipsclass->subtitle = $this->ipsclass->lang['raffle_prev_raffle'];
		$this->ipsclass->nav = array("<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}'>".$this->plugin['name']."</a>","<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}&ampdo=drawn'>".$this->ipsclass->lang['raffle_prev_raffle']."</a>");
		
		$LIMIT = 25;
		$total = $this->ipsclass->DB->build_and_exec_query(array('select'=>'COUNT(*) as total','from'=>'market_raffle','where'=>"r_status='drawn'"));
		$page_links = $this->ipsclass->build_pagelinks(	array(	'TOTAL_POSS'   => $total['total'],
																'PER_PAGE'     => $LIMIT,
																'CUR_ST_VAL'   => $this->ipsclass->input['st'],
																'L_SINGLE'     => $this->ipsclass->compiled_templates['skin_global']->pagination_compile($this->ipsclass->compiled_templates['skin_global']->pagination_make_jump(),"","",$this->ipsclass->compiled_templates['skin_global']->pagination_current_page(1),"","",1,$LIMIT,$this->ipsclass->market_class->base_url."plugin=".$this->ipsclass->input['plugin']."&amp;do=finished",0,'st'),
																'BASE_URL'     => $this->ipsclass->market_class->base_url."plugin=".$this->ipsclass->input['plugin']."&amp;do=finished",
																'USE_ST'       => 'st',
														)	);
		
		$raffles = array();
		$this->ipsclass->DB->build_query(array(
												'select' => 'r.*',
												'from' => array('market_raffle'=>'r'),
												'add_join' => array(
																		array(
																				'select' => 'COUNT(t.t_id) as tickets',
																				'from' => array('market_raffle_tickets'=>'t'),
																				'where' => "r.r_id=t.raffle_id",
																				'type' => 'left',
																			),
																	),
												'where' => "r.r_status='drawn'",
												'group' => 'r.r_id',
												'order' => 'end_time DESC',
												'limit' => array($this->ipsclass->input['st'],$LIMIT),
										)	);
		$this->ipsclass->DB->exec_query();
		while($raffle = $this->ipsclass->DB->fetch_row())
		{
			$raffle['tickets'] = $this->ipsclass->numbers->do_number_format($raffle['tickets']);
			$raffle['drawing'] = $this->ipsclass->get_date($raffle['end_time'],'LONG');
			$raffle['price'] = $this->ipsclass->numbers->format_currency($raffle['r_price']);
			$raffles[] = $raffle;
		}
		
		$this->ipsclass->output .= $this->ipsclass->compiled_templates['skin_market_plugin']->raffle_drawn_page($raffles,$page_links);
	}
}
?>